import { computed, ref } from "vue"
import type { Ref } from 'vue'

import type { HoldItem } from '@/indexDB/initHold'

export type RangeType = 'value' | 'timeLong' | 'earnings'

export const useRange = (filteredHoldList: Ref<HoldItem[]>) => {
  const rangeBy = ref<RangeType>('value')
  const setRangeBy = (type: RangeType) => {
    rangeBy.value = type
  }
  const RANGE_MAP: Record<RangeType, keyof HoldItem> = {
    value: 'holdValue',
    timeLong: 'createTime',
    earnings: 'holdEarnings'
  }
  const rangedList = computed(() => {
    const rangeKey = RANGE_MAP[rangeBy.value]
    return filteredHoldList.value.sort((before, after) => {
      const beforeValue = +(before[rangeKey] || 0) as number
      const afterValue = +(after[rangeKey] || 0) as number
      return afterValue - beforeValue
    }).slice(0, 3)
  })

  return {
    rangeBy,
    setRangeBy,
    rangedList
  }
}